<template>
  <div class="Qr">
    <img :src="imageCode" alt="" />
    <div>
      <span>扫码状态:</span>
      <span v-if="code !== 800">{{ codeStatus }}</span>
      <span class="refresh" @click="getKey()" v-else><u>二维码过期，点击刷新</u></span>
    </div>
  </div>
</template>

<script>
import { mapMutations } from 'vuex';
export default {
  data() {
    return {
      key: '',
      imageCode: '',
      code: '',
      codeStatus: '',
    };
  },
  created() {
    //组件创建调取二维码
    this.getKey();
  },
  methods: {
    ...mapMutations(['changeLogin']),
    async getKey() {
      //获取key
      let res = await this.$request('/login/qr/key', { timestamp: Date.now() });
      this.key = res.data.unikey;
      this.getQrCode();
    },
    //生成二维码图片
    async getQrCode() {
      let res = await this.$request('/login/qr/create', { key: this.key, qrimg: true, timestamp: Date.now() });
      this.imageCode = res.data.qrimg;
      this.checkCode();
    },
    //轮询此接口可获取二维码扫码状态,800 为二维码过期,801 为等待扫码,802 为待确认,803 为授权登录成功(803 状态码下会返回 cookies)
    async checkCode() {
      let res = await this.$request('/login/qr/check', { key: this.key, timestamp: Date.now() });
      this.code = res.code;
      this.codeStatus = res.message;
      if (res.code === 801 || res.code === 802) {
        this.timer = window.setTimeout(() => {
          this.checkCode();
        }, 5000);
      } else if (res.code === 803) {
        //803授权登录成功，获取账号信息---此处因为登录状态获取较慢的问题无法正确获取到登陆状态，所以只能跳过登陆状态直接获取账号信息
        this.$store.dispatch('getAccount');
        //更新登录状态
        this.changeLogin(true);
        //关闭对话框
        this.$emit('closeDialog');
      }
    },
  },
  beforeDestroy() {
    //组件销毁，清除定时器
    window.clearTimeout(this.timer);
  },
};
</script>

<style lang='scss' scoped>
.Qr {
  text-align: center;
  .refresh {
    color: $themeColor;
    cursor: pointer;
  }
}
</style>